#!/bin/bash

# GitHub repository details
GITHUB_OWNER="delta-incubator"
GITHUB_REPO="delta-docs"

# Check if GitHub token is available
if [ -z "$GITHUB_TOKEN" ]; then
    echo "Error: GITHUB_TOKEN environment variable is required for downloading artifacts"
    echo "Please set GITHUB_TOKEN with a personal access token that has scope: public_repo, actions:read"
    exit 1
fi

# Check if an argument was provided
if [ -z "$1" ]; then
    echo "Error: No version argument provided"
    echo "Usage: $0 <version>"
    exit 1
fi

# Get the first argument (e.g., "latest")
arg="$1"

# Concatenate with the environment variable prefix
env_var_name="npm_package_config_apidocs_${arg}"

# Get the value of the dynamically constructed environment variable
apidocs_version="${!env_var_name}"

# Check if the environment variable exists and has a value
if [ -z "$apidocs_version" ]; then
    echo "Error: No configuration found for version '$arg'"
    echo "Environment variable '$env_var_name' is not set or empty"
    echo "Supported versions should be configured in package.json"
    echo "Available versions: latest, v3, v2"
    exit 1
fi

echo "Resolved version '$arg' to '$apidocs_version'"

# GitHub API base URL
api_base_url="https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}"

# Create target directory path
target_dir="public/api/${apidocs_version}"
zip_file="${apidocs_version}.zip"

# Create public/api directory if it doesn't exist
mkdir -p public/api

# Remove existing target directory if it exists (for idempotence)
if [ -d "$target_dir" ]; then
    echo "Removing existing directory: $target_dir"
    rm -rf "$target_dir"
fi

# First, get the list of artifacts to find the one matching our version
echo "Searching for artifact with name containing '$apidocs_version'..."
artifacts_response=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \
    -H "Accept: application/vnd.github.v3+json" \
    "$api_base_url/actions/artifacts")

if [ $? -ne 0 ]; then
    echo "Error: Failed to fetch artifacts list from GitHub API"
    exit 1
fi

# Extract artifact ID for the matching version (assumes artifact name contains the version)
artifact_id=$(echo "$artifacts_response" | grep -A 10 -B 10 "\"name\".*$apidocs_version" | grep '"id"' | head -1 | sed 's/.*"id": *\([0-9]*\).*/\1/')

if [ -z "$artifact_id" ]; then
    echo "Error: No artifact found with name containing '$apidocs_version'"
    echo "Available artifacts:"
    echo "$artifacts_response" | grep '"name"' | sed 's/.*"name": *"\([^"]*\)".*/  - \1/'
    exit 1
fi

echo "Found artifact ID: $artifact_id"

# Download the artifact
echo "Downloading artifact $artifact_id..."
download_url="$api_base_url/actions/artifacts/$artifact_id/zip"
echo "Download URL: $download_url"

if ! curl -L -H "Authorization: token $GITHUB_TOKEN" \
    -H "Accept: application/vnd.github.v3+json" \
    -o "$zip_file" "$download_url"; then
    echo "Error: Failed to download artifact from $download_url"
    echo "Please check if the artifact exists and your token has proper permissions"
    exit 1
fi

# Verify the downloaded file exists and is not empty
if [ ! -s "$zip_file" ]; then
    echo "Error: Downloaded file is empty or does not exist"
    rm -f "$zip_file"
    exit 1
fi

# Create target directory
mkdir -p "$target_dir"

# Extract the archive
echo "Extracting to $target_dir..."
if ! unzip -o "$zip_file" -d "$target_dir"; then
    echo "Error: Failed to extract $zip_file"
    rm -f "$zip_file"
    rm -rf "$target_dir"
    exit 1
fi

# Clean up the zip file
rm -f "$zip_file"

echo "Successfully extracted API docs for version '$apidocs_version' to '$target_dir'"
echo "Done!"